//
//  ForGetPassWordVC.m
//  Inforcollection
//
//  Created by macbook on 16/2/2.
//  Copyright © 2016年 oceansoft.liw. All rights reserved.
//

#import "ForGetPassWordVC.h"

#import "ForGetPassWordCell.h"

#import "ForGetPassWordGetCodeCell.h"

#import "UIView+Toast.h"

@interface ForGetPassWordVC ()

@property (nonatomic,strong)NSArray *nameArray;

@property (nonatomic,strong)NSArray *placeholderArray;

@property (nonatomic,strong)NSMutableArray *textFieldArray;

@property (nonatomic,strong)NSString *passWord;

@property (nonatomic)NSTimer *getCodeTimer;

@property (nonatomic)int stayTime;

@property (nonatomic)UILabel *getCodeLable;

@property (nonatomic,strong)NSString *telStr;

@property (nonatomic,strong)NSString *codeStr;

@end

@implementation ForGetPassWordVC

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    [self initViews];
    
    [self initMutDicAndArray];
}

-(void)initViews
{
    [self setNaviBarTitle:@"忘记密码"];
    
    [self.mainTableView registerNib:[UINib nibWithNibName:@"ForGetPassWordCell" bundle:nil] forCellReuseIdentifier:@"ForGetPassWordCell"];
    
    [self.mainTableView registerNib:[UINib nibWithNibName:@"ForGetPassWordGetCodeCell" bundle:nil] forCellReuseIdentifier:@"ForGetPassWordGetCodeCell"];
    
    self.mainTableView.backgroundColor=KTableViewBackColor;
    
    self.mainTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    [[UITableViewHeaderFooterView appearance]setTintColor:KTableViewBackColor];
    
    [self addSubmitButton];
}
-(void)addSubmitButton
{
    UIView *bottomView = [[UIView alloc]init];
    
    bottomView.backgroundColor = [UIColor clearColor];
    
    bottomView.frame = CGRectMake(0, 0, ScreenWidth, 50);
    
    UIButton *submitButton = [[UIButton alloc]init];
    
    submitButton.frame = CGRectMake(10, 5, ScreenWidth-20, 40);
    
    submitButton.backgroundColor = KButtonBackColor;
    
    [submitButton setTitle:@"提交找回" forState:UIControlStateNormal];
    
    submitButton.layer.cornerRadius = 5.0;
    
    [submitButton addTarget:self action:@selector(submitGetPassWord) forControlEvents:UIControlEventTouchUpInside];
    
    [bottomView addSubview:submitButton];
    
    [self.mainTableView setTableFooterView:bottomView];
}
-(void)initMutDicAndArray
{
    _nameArray = [NSArray arrayWithObjects:@"手机号码",@"验  证  码",@"密       码",@"确认密码",nil];
    
    _placeholderArray = [NSArray arrayWithObjects:@"请输入手机号码",@"请输入验证码",@"请输入新的密码",@"请再次确认密码",nil];
    
    _textFieldArray = [NSMutableArray array];
    
    _stayTime = KGetCodeStayTime;
}

#pragma mark- -------TableView DataSource And DeleGate

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _nameArray.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row != 1) {
    
    ForGetPassWordCell *cell=[tableView dequeueReusableCellWithIdentifier:@"ForGetPassWordCell"];
    
        if (cell==nil)
        {
            cell=[[ForGetPassWordCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"ForGetPassWordCell"];
        }
    
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        
        cell.nameLabel.text = _nameArray[indexPath.row];
        
        cell.mainTextField.placeholder = _placeholderArray[indexPath.row];
        
        cell.mainTextField.delegate = self;
        
        
        if (indexPath.row==0)
        {
            cell.mainTextField.keyboardType = UIKeyboardTypeNumberPad;
        }
        if (indexPath.row==2 || indexPath.row==3)
        {
            cell.mainTextField.secureTextEntry=YES;
        }
        
        [_textFieldArray addObject:cell.mainTextField];
        
        return cell;
    }
    else
    {
        ForGetPassWordGetCodeCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ForGetPassWordGetCodeCell"];
        
        if (cell==nil)
        {
            cell = [[ForGetPassWordGetCodeCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"ForGetPassWordGetCodeCell"];
        }
        cell.selectionStyle = UITableViewCellSelectionStyleNone;

        cell.nameLabel.text = _nameArray[indexPath.row];
        
        cell.mainTextField.placeholder = _placeholderArray[indexPath.row];
        
        cell.mainTextField.delegate = self;
        
        UITapGestureRecognizer *ges = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(requestCode)];
        
        [cell.getCodeLable addGestureRecognizer:ges];
        
        self.getCodeLable = cell.getCodeLable;
        
        [_textFieldArray addObject:cell.mainTextField];

        return cell;
    }
}

-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    if ([string isEqualToString:@"\n"])
    {
        return YES;
    }
    NSString *currentString = [textField.text stringByReplacingCharactersInRange:range withString:string];
    if (textField == _textFieldArray[0])
    {
        if (currentString.length>11)
        {
            return NO;
        }
    }
    if (textField == _textFieldArray[1] || textField == _textFieldArray[2]) {
        if (currentString.length>16)
        {
            return NO;
        }
    }
    if (textField == _textFieldArray[3]) {
        if (currentString.length>6) {
            return NO;
        }
    }
    return YES;
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 10;
}

-(void)submitGetPassWord
{
    if ([self checkString])
    {
//        NSDictionary *dict = @{@"mobile":_telStr,@"newPassword":_passWord,@"validateCode":_codeStr};
//        [[HttpAPI shareHttpAPI]forgetPassWordWithDict:dict CallBack:^(NSDictionary *receivedData)
//        {
//            if (receivedData!=nil && [receivedData[@"succ"]boolValue])
//            {
//                [MBProgressHUD showHUDAddedTo:SharedApplication.keyWindow text:receivedData[@"msg"] duration:1.5 whileExecutingBlock:nil];
//                
//                [self.navigationController popViewControllerAnimated:YES];
//            }
//            else
//            {
//                [MBProgressHUD showHUDAddedTo:SharedApplication.keyWindow text:receivedData[@"msg"] duration:1.5 whileExecutingBlock:nil];
//            }
//        }];
    }
}
-(BOOL)checkString
{
    for (int i = 0; i<_textFieldArray.count; i++)
    {
        UITextField *field = _textFieldArray[i];
        
        NSString *str = [self removeSpaceWithString:field.text];
        
        if (str!=nil && ![str isEqualToString:@""] && ![str isKindOfClass:[NSNull class]])
        {
            if (i==0)
            {
                _telStr = str;
                if (![self checkTel:str])
                {
                    return NO;
                }
            }
            else if (i==2)
            {
                _passWord = str;
                
                if (str.length<3 || str.length>16)
                {
                    [self.view makeToast:@"请输入正确的密码"];
                    
                    return NO;
                }
            }
            else if (i==3)
            {
                if (![str isEqualToString:_passWord])
                {
                    [self.view makeToast:@"输入的确认密码不正确"];
                    return NO;
                }
            }
            else if (i==1)
            {
                _codeStr = str;
                if (str.length != 6)
                {
                    [self.view makeToast:@"请输入正确的验证码"];
                    return NO;
                }
            }
        }
        else//出现空字符的时候进行这一步
        {
            [self.view makeToast:_placeholderArray[i]];
            
            return NO;
        }
        
        
    }
    return YES;
}
- (void)getCode
{
    _getCodeTimer = [NSTimer timerWithTimeInterval:1.0 target:self selector:@selector(timerStart) userInfo:nil repeats:YES];
    [[NSRunLoop currentRunLoop]addTimer:_getCodeTimer forMode:NSRunLoopCommonModes];
}

- (void)requestCode
{
    UITextField *textField = self.textFieldArray[0];
    
    NSString *telString = [textField.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    
    if (telString.length == 0)
    {
        [MBProgressHUD showHUDAddedTo:SharedApplication.keyWindow text:@"请输入手机号码" duration:1.5 whileExecutingBlock:nil];
        return;
    }
    else if (telString.length!=11)
    {
        [MBProgressHUD showHUDAddedTo:SharedApplication.keyWindow text:@"请输入正确的手机号码" duration:1.5 whileExecutingBlock:nil];
        return;
    }
    
    NSDictionary *postDic = @{@"tel":textField.text,@"type":@"3",@"content":@"",@"expire":@"60"};
    
    [[HttpAPI shareHttpAPI] getYZMWithDic:postDic CallBack:^(NSDictionary *receivedData)
     {
         if (receivedData != nil)
         {
             [MBProgressHUD showHUDAddedTo:SharedApplication.keyWindow text:receivedData[@"msg"] duration:1.5 whileExecutingBlock:nil];
             
                 self.getCodeLable.userInteractionEnabled = NO;
                 
                 [self getCode];
        }
    }];

}

-(void)timerStart
{
    if (_stayTime == 0)
    {
        self.getCodeLable.userInteractionEnabled = YES;
        
        self.getCodeLable.text = @"获取验证码";
        
        [_getCodeTimer invalidate];
        
        _stayTime = KGetCodeStayTime;
    }
    else
    {
        self.getCodeLable.userInteractionEnabled = NO;
        
        _stayTime--;
        
        self.getCodeLable.text = [NSString stringWithFormat:@"%d 秒",_stayTime];
    }
}
@end
